﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ERP.Manager.BusinessServices;
using ERP.Manager.DataEntity;
using ERP.Manager.Controllers.CustomAttributes;
using System.Drawing;
using System.Drawing.Imaging;
namespace ERP.Manager.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        private readonly UserinfoService userService;
        private readonly LoginService loginService;
        private readonly ContextService contextservice;
        private readonly MessageinfoService messageService;
        public HomeController() { }


        public HomeController(UserinfoService userservice, LoginService loginservice, ContextService contextservice, MessageinfoService messageservice)
        {
            this.userService = userservice;
            this.loginService = loginservice;
            this.contextservice = contextservice;
            this.messageService = messageservice;
        }
        #region 主页面
        [CheckLoginAttribute]
        public ActionResult Index()
        {
            ViewData["Message"] = "欢迎使用企业管理系统！";
            return View();
        }
        #endregion

        #region 登录页面
        public ActionResult Login()
        {

            return View();
        }
        #endregion

        #region 登录提交
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult doLog(FormCollection FormValue)
        {
            try
            {
                var login = userService.userLogin(FormValue["userName"].Trim(), FormValue["password"].Trim());
                var session = loginService.InitializeUserDataInSession(FormValue["userName"].Trim());
                string validator = Request.Form["txtuservalidator"];
                if (login && session)
                {
                    if (login == true)
                    {
                        if (validator.ToLower() != (Session["validator"].ToString().ToLower()))
                        {
                            ModelState.AddModelError("validateuserName", "您输入的验证码有误！");
                            return View("Login");
                        }
                        return this.RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        return this.RedirectToAction("Login", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("validateuserName", "您的用户名和密码有误！！");
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("validateuserName", "" + ex.Message + "");
            }
            return View("Login");
        }
        #endregion

        #region 权限错误页面
        public ActionResult CheckError()
        {
            return View("");
        }
        #endregion

        #region 操作错误页面
        public ActionResult error()
        {
            return View();
        }
        #endregion

        #region 退出系统的方法
        public string tuichuxitong()
        {
            try
            {
                //清空当前会话跟踪；
                HttpContext.Session.Clear();
                return "success";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        #endregion

        #region OA系统首页顶部
        public ActionResult Top()
        {
            return View();
        }
        #endregion

        #region OA系统首页中部
        public ActionResult Middel()
        {
            return View();
        }
        #endregion

        #region  OA系统首页中部的菜单和内容
        public ActionResult Center()
        {
            return View();
        }
        #endregion

        #region OA系统首页中部左边
        [CheckLoginAttribute]
        public ActionResult Left()
        {
            return View();
        }
        #endregion

        #region OA系统首页中部右边
        [CheckLoginAttribute]
        public ActionResult Right()
        {
            string UserId = contextservice.UserId;
            UserInfo userinfo = userService.DetailUserinfo(UserId);
            ViewData["userinfo"] = userinfo;
            ViewData["messages"] = messageService.getMessagesToIndex();
            //查询最新公告的第一条信息
            Messageinfo me = new Messageinfo();
            List<Messageinfo> list = messageService.getAllMessages(1);
            foreach (var item in list)
            {
                me.messageId = item.messageId;
                me.messageTitle = item.messageTitle;
                me.messageContent = item.messageContent;
                me.publishDate = item.publishDate;
                break;
            }
            ViewData["message"] = me;
            return View();
        }
        #endregion

        #region OA系统首页底部
        public ActionResult Down()
        {
            return View();
        }
        #endregion

        #region 生成验证码
        public void LoginImage()
        {
            //建立我们的画板；
            Bitmap bitmap = new Bitmap(80, 30);
            //建立画布；
            Graphics graphics = Graphics.FromImage(bitmap);
            //填充画布；
            graphics.FillRectangle(Brushes.White, 0, 0, 80, 30);
            //设置字体和字体的大小；
            Font font = new Font("楷体", 16);
            //定义一组字符串；
            string letters = "ABCD2EF3G4HJ5KLM6NP7QLS8TUV9WXYZ";
            //定义变量，接收随机生成的字符；累加的；
            StringBuilder sb = new StringBuilder();
            //定义变量，接收随机生成数；
            Random rand = new Random();
            string result = string.Empty;
            //产生4个随机字符，组成验证码；
            for (int i = 0; i < 4; i++)
            {
                //把随机生成的字符赋值到result变量中；
                result = letters.Substring(rand.Next(0, letters.Length - 1), 1);
                //在把result值追加到随机生成的字符中；
                sb.Append(result);
                //把我们生成的字符绘制到图片上去；
                graphics.DrawString(result, font, Brushes.Red, i * 15, rand.Next(0, 10));
            }
            //将生成的验证码图片保存到画板；
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            HttpContext.Session["validator"] = sb.ToString();
            //设置响应流输出的类型；
            Response.ContentType = "image/gif";
            Response.BinaryWrite(ms.ToArray());
        }
        #endregion
    }
}
